class Admin::ImagesController < Admin::AdminController
  before_action :find_imageable, except: [:create_image]

  def create
    image = Image.new(image_params)
    if image.save
      render json: image
    else
      render json: image.errors, status: 422
    end
  end

  def create_image
    image = Image.new(image_a_params)
    if image.save
      render json: image
    else
      render json: image.errors, status: 422
    end
  end

  def update
    image = Image.find(params[:id])
    if image.update(image_params)
      render json: {result: 'success'}
    else
      render json: {result: 'error'}
    end
  end

  def destroy
    Image.destroy(params[:id])
    render json: []
  end

  private
  def image_a_params
    params.permit(:file, :imageable_type, :desc)
  end

  def image_params
    params.permit(:file, :imageable_type, :desc).merge(imageable: @imageable)
  end

  def find_imageable
    resource, id = request.path.split('/')[2, 2]
    @imageable = resource.classify.constantize.find(id)
  end
end
